<template>
  <div class='page-container'>
    <el-button @click="downTemplate">下载导入模板</el-button>
    <div style="margin-top: 15px;">
      <span>上传模板</span>
      <UploadExcel @on-selected-file='selected'></UploadExcel>
    </div>
  </div>
</template>

<script>
import API from '@/api/importDemo'
import { download } from '@/utils'
import UploadExcel from '@/components/UploadExcel'

export default {
  components: {
    UploadExcel
  },
  data () {
    return {
      genderMap: new Map().set('男', 0).set('女', 1), // 性别
      addList: [], // 通过验证的数据
      errList: []// 错误数据
    }
  },
  computed: {},
  methods: {
    // 下载模板
    downTemplate () {
      API.downTemplate().then(res => {
        let fileName = '导入的模板'
        download(res.data, fileName)
      }).catch(e => {
        this.$message.error(`error:${e.message}`)
      })
    },
    //
    selected (data) {
      let result = data.results
      result.shift()
      for (let res of result) {
        let errorInfo = ''
        // 用户名
        if (res.userName) {
          if (res.userName.length > 32) {
            errorInfo += '用户名最多只能输入32个字'
          }
        } else {
          errorInfo += '用户名为空'
        }
        // 身份证
        // 身份证正则表达式(15位)
        const isIDCard1 = /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$/
        // 身份证正则表达式(18位)
        const isIDCard2 = /^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{4}$/
        if (res.identityNumber && !isIDCard1.test(res.identityNumber) && !isIDCard2.test(res.identityNumber)) {
          errorInfo += '身份证格式错误'
        }

        // 性别
        if (res.gender && !this.genderMap.has(res.gender)) {
          errorInfo += '性别输入错误'
        }

        // 判断错误信息是否为空
        if (errorInfo.length) {
          res.errorInfo = errorInfo
          this.errList.push(res)
        } else {
          res.gender = this.genderMap.get(res.gender)
          this.addList.push(res)
        }
      }
      API.importUserInfo(this.addList).then(res => {

      }).catch(e => {
        this.$message.error(`error:${e.message}`)
      })
    }
  },
  mounted () {

  }
}
</script>
<style lang='less' scoped>
.page-container {
  padding: 15px;
}
</style>
